/*
 * charging.h
 *
 * charging module, inlcude init etc..
 *
 * Copyright (C) 2022 Microwell, Inc.
 * Subject to the GNU Public License, version 2.
 *
 * Author: guoming<guoming@microwell.net>
 */
#ifndef __CHARGING_H__
#define __CHARGING_H__

#include "core.h"

#define VSTOP_30MV                       (0x08)
#define VSTOP_60MV                       (0x04)

/*=============================================================================
 *                             Charging config
 *===========================================================================*/
/* Battery's max charge current, should not larger than 800mA */
#if (CONFIG_DC_CHARGER_MAX_CURRENT > 800)
#error("CONFIG_DC_CHARGER_MAX_CURRENT should not larger than 800")
#endif

#define CONFIG_CHARGER_USING_RCHG        (1)

/* Chargering full voltage:
 * VSTOP_60 VSET-60mV, VSTOP_30 VSET-30mV */
#define CONFIG_CHARGER_VSTOP             (VSTOP_30MV)

/* Charger current(CC current) set:
 * 0 50mA, 1 100mA, 2 150mA, ..., F 800mA */
/* charger current only with DCIN */
#define CONFIG_CHARGER_ISET_DC           (CONFIG_DC_CHARGER_MAX_CURRENT / 50 -1)
/* Charger voltage(CV voltage) set, refer to CHGCON1 */
#if (CONFIG_BAT_FULL_VOLTAGE == 4200)
#define CONFIG_CHARGER_VSET              (VSET_4V20)
#elif (CONFIG_BAT_FULL_VOLTAGE == 4350)
#define CONFIG_CHARGER_VSET              (VSET_4V35)
#elif (CONFIG_BAT_FULL_VOLTAGE == 4400)
#define CONFIG_CHARGER_VSET              (VSET_4V40)
#elif (CONFIG_BAT_FULL_VOLTAGE == 4450)
#define CONFIG_CHARGER_VSET              (VSET_4V45)
#else
#error ("Please set CONFIG_CHARGER_VSET according to CONFIG_BAT_FULL_VOLTAGE")
#endif

#if (CONFIG_CHARGER_VSTOP == VSTOP_60MV)
#define CHARGER_FULL_VOL    (CONFIG_BAT_FULL_VOLTAGE - 60)
#elif (CONFIG_CHARGER_VSTOP == VSTOP_30MV)
#define CHARGER_FULL_VOL    (CONFIG_BAT_FULL_VOLTAGE - 30)
#else
    #error("CONFIG_USING_CHARGER is error")
#endif
/*=============================================================================
 *                             Charging end
 *===========================================================================*/

#define CHARGING_ISET_READ()             (READ_BIT(CHGCON0, CLR_ISET) >> 4)
#define CHARGING_ISET(ISET)              MODIFY_REG(CHGCON0, CLR_ISET, (ISET << 4))

#define CHARGING_ENABLE()                SET_BIT(CHGCON0, CHG_EN)
#define CHARGING_DISABLE()               CLEAR_BIT(CHGCON0, CHG_EN)

#define IS_CHARGING_ENABLE()             (!!READ_BIT(CHGCON0, CHG_EN))
#define IS_CHARGING_CHARGING()           (!!READ_BIT(CHGSTAT, CHGON))
#define IS_CHARGING_TIMEOUT()            (!!READ_BIT(CHGSTAT, CHGTO))
#define IS_CHARGING_FULL()               (!!READ_BIT(CHGSTAT, CHGFULL))

#if (CONFIG_USING_CHARGER == 1)
void charging_init(void);
void charging_exit(void);
void charging_current_set(uint8_t iset);
#else
#define charging_init()
#define charging_exit()
#define charging_current_set(iset)        (iset)
#endif

#endif